﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Warensoft.Unity.Communication.Client.Contracts;
using Warensoft.Unity.Communication.Client.Models;

namespace Warensoft.Unity.Communication.Client
{
    public class HttpPackageManager:PackageManagerBase
    {
        protected override object[] ProcessQueueToPackage()
        {
            List<HttpResponse> result = new List<HttpResponse>();

            while (true)
            {
                var tmpBuffer = this.messageQueue.ToArray();
                string content = System.Text.Encoding.UTF8.GetString(tmpBuffer);
                int contentIndex = content.IndexOf("\r\n\r\n");
                if (contentIndex != -1)
                {
                    TextReader reader = new StringReader(content.Substring(0, contentIndex));
                    string line = reader.ReadLine();
                    HttpResponse response = new HttpResponse();
                    response.Headers = new Dictionary<string, string>();
                    response.responseLine = line;
                    var status =int.Parse ( line.Split(' ')[1]);
                    response.status = status;
                    while (line != null)
                    {

                        line = reader.ReadLine();
                        if (line != null)
                        {
                            response.Headers.Add(line.Split(':')[0].ToLower(), line.Split(':')[1]);
                        }
                    }
                    var length = int.Parse(response.Headers["content-length"]);
                    if (contentIndex + length + 4 <= tmpBuffer.Length)
                    {
                        response.Data = tmpBuffer.Skip(contentIndex + 4).Take(length).ToArray();
                        result.Add(response);
                        for (int i = 0; i < contentIndex + length + 4; i++)
                        {
                            this.messageQueue.Dequeue();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            
            return result.ToArray ();
        }
    }
}
